from django.db import models
from django.core.exceptions import ValidationError
from users.models import Supplier

class Category(models.Model):
    name = models.CharField(max_length=50, verbose_name='类别名称')
    description = models.TextField(verbose_name='类别描述', blank=True)
    
    class Meta:
        verbose_name = '产品类别'
        verbose_name_plural = verbose_name
        
    def __str__(self):
        return self.name

class Product(models.Model):
    name = models.CharField(max_length=100, verbose_name='产品名称')
    category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='products', verbose_name='产品类别')
    supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE, related_name='products', verbose_name='供应商')
    production_batch = models.CharField(max_length=50, verbose_name='生产批次号', default='', unique=True)
    trace_id = models.CharField(max_length=100, verbose_name='溯源ID', unique=True, null=True, blank=True)
    price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='价格')
    unit = models.CharField(max_length=20, verbose_name='单位')
    shelf_life = models.IntegerField(verbose_name='保质期(天)')
    storage_temp = models.DecimalField(max_digits=5, decimal_places=2, verbose_name='存储温度(℃)')
    inventory = models.PositiveIntegerField(default=0, verbose_name='库存数量')
    description = models.TextField(verbose_name='产品描述', blank=True)
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        verbose_name = '产品'
        verbose_name_plural = verbose_name
        
    def __str__(self):
        return self.name

    def clean(self):
        if self.inventory <= 10:
            raise ValidationError('库存已低于预警值，请及时补货。')
